<?php
namespace app\admin\controller;
use app\admin\model\IndexTableModel;
use app\admin\model\JoinTableModel;
use app\admin\controller\Cloudaccountwithdraw;
use think\Db;
use think\Request;
use app\common\model\User;
use app\common\model\UserLevel;
use app\common\validate\UserValidate;

require_once (__DIR__.'/../../../vendor/ReidsLock.class.php');
class FinanceController extends Controller
{

    /**
     * 财务日志列表
     * User:@hang
     */
    public function index(Request $request)
    {
        $param = $request->param();
        $whehe = array();
        $zhuanwhere = array();
        if (isset($param['member_id']) && !empty($param['member_id'])) {
            $whehe[] = ['b.member_id','=',$param['member_id']];
            $zhuanwhere[] = ['b.member_id','=',$param['member_id']];
        }
        if (isset($param['me_uid']) && !empty($param['me_uid'])) {
            $whehe[] = ['b.me_uid','=',$param['me_uid']];
            $zhuanwhere[] = ['b.me_uid','=',$param['me_uid']];
        }
        if (isset($param['me_phone']) && !empty($param['me_phone'])) {
            $whehe[] = ['b.me_phone|b.me_nick_name','like',"%{$param['me_phone']}%"];
            $zhuanwhere[] = ['b.me_phone|b.me_nick_name','like',"%{$param['me_phone']}%"];
        }

        $wheretype = '';
        //收入可提现油票 搜索
        if(!empty($param['k_stamp_income'])){
            $wheretype .= " or (a.type = '{$param['k_stamp_income']}' and a.status = 1 and a.money_type = 2)";
        }
        //收入不可提现油票
        if(!empty($param['bk_stamp_income'])){
            $wheretype .= " or (a.type = '{$param['bk_stamp_income']}' and a.status = 1 and a.money_type = 1)";
        }
        //支出可 提现或不可提现 油票
        if(!empty($param['stamp_disburse'])){
            $wheretype .= " or (a.type = '{$param['stamp_disburse']}' and a.status = 2 and a.money_type in(1,2))";
        }
        //曝光收入
        if(!empty($param['exposure_income'])){
            $wheretype .= " or (a.type = '{$param['exposure_income']}' and a.status = 1 and a.money_type = 3)";
        }
        //曝光支出
        if(!empty($param['exposure_disburse'])){
            $wheretype .= " or (a.type = '{$param['exposure_disburse']}' and a.status = 2 and a.money_type = 3)";
        }
        $wheretype = trim($wheretype,' or ');

//        if (isset($param['type']) && !empty($param['type'])) {
//            $whehe[] = ['c.type','=',$param['type']];
//        }
//        if (isset($param['money_type']) && !empty($param['money_type'])) {
//            $whehe[] = ['a.money_type','=',$param['money_type']];
//        }
//        if (isset($param['status']) && !empty($param['status'])) {
//            $whehe[] = ['a.status','=',$param['status']];
//        }
        $whehetime = '';
        if (isset($param['add_time']) && !empty($param['add_time'])) {
            $time_arr = explode(' - ', $param['add_time']);
            $start_time = strtotime($time_arr[0]);
            $end_time = strtotime($time_arr[1]);
            $whehetime = "a.add_time >= $start_time AND a.add_time <= $end_time";
        }
//        var_dump($param);die;
        if (isset($param['d_member_id']) && !empty($param['d_member_id'])) {
            $whehe[] = ['a.d_member_id','=',$param['d_member_id']];
        }
        if (isset($param['d_me_uid']) && !empty($param['d_me_uid'])) {
            $whehe[] = ['d.me_uid','=',$param['me_uid']];
        }
        if (isset($param['d_me_phone']) && !empty($param['d_me_phone'])) {
            $whehe[] = ['d.me_phone|d.me_nick_name','like',"%{$param['d_me_phone']}%"];
        }
        $zhuanword = '';
        $txword = '';
        $mqword = '';
        if(!empty($zhuanwhere)){
            //文字音视频收入
            $wzZhuan = Db::table('fa_finance')
                ->alias('a')
                ->join("fa_member b",'a.member_id = b.member_id','LEFT')
                ->join("fa_member d",'a.d_member_id = d.member_id','LEFT')
                ->where($whehe)
                ->where($zhuanwhere)
                ->where($whehetime)
                ->where("a.money_type = 2 and a.status = 1 and a.chat_type != 0")
                ->sum('money');
            //礼物收入
            $lwZhuan = Db::table('fa_finance')
                ->alias('a')
                ->join("fa_member b",'a.member_id = b.member_id','LEFT')
                ->join("fa_member d",'a.d_member_id = d.member_id','LEFT')
                ->where($whehe)
                ->where($zhuanwhere)
                ->where($whehetime)
                ->where("a.money_type = 2 and a.status = 1 and a.type = 13")
                ->sum('money');
            //下级充值奖励收入
            $czZhuan = Db::table('fa_finance')
                ->alias('a')
                ->join("fa_member b",'a.member_id = b.member_id','LEFT')
                ->join("fa_member d",'a.d_member_id = d.member_id','LEFT')
                ->where($whehe)
                ->where($zhuanwhere)
                ->where($whehetime)
                ->where("a.money_type = 2 and a.status = 1 and a.rebate_type != 0 and a.chat_type = 0")
                ->sum('money');
            //下级聊天奖励收入
            $xjltZhuan = Db::table('fa_finance')
                ->alias('a')
                ->join("fa_member b",'a.member_id = b.member_id','LEFT')
                ->join("fa_member d",'a.d_member_id = d.member_id','LEFT')
                ->where($whehe)
                ->where($zhuanwhere)
                ->where($whehetime)
                ->where("a.money_type = 2 and a.status = 1 and a.rebate_type != 0 and a.chat_type != 0")
                ->sum('money');
            //充值奖励收入
            $allZhuan = delete0(bcadd(bcadd(bcadd($wzZhuan,$lwZhuan,4),$czZhuan,4),$xjltZhuan,4));
            //提现通过
            $tgTx = Db::table('fa_zwithdrawal_order')
                ->alias('a')
                ->join("fa_member b",'a.member_id = b.member_id','LEFT')
                ->where($zhuanwhere)
                ->where($whehetime)
                ->where("a.status = 1")
                ->sum('total_withdrawal');
            //提现拒绝
            $jjTx = Db::table('fa_zwithdrawal_order')
                ->alias('a')
                ->join("fa_member b",'a.member_id = b.member_id','LEFT')
                ->where($zhuanwhere)
                ->where($whehetime)
                ->where("a.status = 2")
                ->sum('total_withdrawal');
            //提现待审核
            $dshTx = Db::table('fa_zwithdrawal_order')
                ->alias('a')
                ->join("fa_member b",'a.member_id = b.member_id','LEFT')
                ->where($zhuanwhere)
                ->where($whehetime)
                ->where("a.status = 0")
                ->sum('total_withdrawal');
            //当前剩余
            $mqSy = Db::table('fa_member_fund')
                ->alias('a')
                ->join("fa_member b",'a.member_id = b.member_id','LEFT')
                ->where($zhuanwhere)
                ->field('a.stamp_money')
                ->find();
            $mqSy = !empty($mqSy)?$mqSy['stamp_money']:'未查询到用户';

            $zhuanword = "【文字音视频收入：$wzZhuan 】 【礼物收入：$lwZhuan 】 【充值奖励收入：$czZhuan 】【下级聊天奖励收入：$xjltZhuan 】 = 【总收入：$allZhuan 】";
            $txword = "【提现通过：$tgTx 】 【提现拒绝：$jjTx 】 【提现待审核：$dshTx 】 ";
            $mqword = "【当前剩余：$mqSy 】";
        }

        $data = Db::table('fa_finance')
            ->alias('a')
            ->join("fa_member b",'a.member_id = b.member_id','LEFT')
            ->join("fa_finance_type c",'a.type = c.id','LEFT')
            ->join("fa_member d",'a.d_member_id = d.member_id','LEFT')
            ->where($whehe)
            ->where($wheretype)
            ->where($whehetime)
            ->field('a.*,b.me_uid,b.me_phone,b.me_nick_name,b.me_sex,c.type as zd_type,c.sz_type as zd_sz,c.name as zd_name,d.me_uid as d_me_uid,d.me_phone as d_me_phone,d.me_nick_name as d_me_nick_name,d.me_sex as d_me_sex')
            ->order('a.add_time desc,a.id desc')
            ->paginate($this->admin['per_page'],false,['query'=>request()->param()]);
        $adminid = $this->uid;
        $data->each(function ($v, $k)use($adminid) {
            //只有超管能看全部手机号
            if($adminid != 1){
                $v['me_phone'] = hide_phone_number($v['me_phone']);
            }
            switch($v['money_type']){
                case '1':
                    if(in_array($v['type'],[34,35])){
                        $v['money_type_word'] = '体验卷';
                    }else{
                        $v['money_type_word'] = '不可提现油票';
                    }
                    break;
                case '2': $v['money_type_word'] = '可提现油票';break;
                case '3': $v['money_type_word'] = '曝光量';break;
            }
            switch($v['status']){
                case '1': $v['status_word'] = '收入';break;
                case '2': $v['status_word'] = '支出';break;
            }
            $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            $typeInfo = $this->getTypeWord($v['zd_name'],$v['status'],$v['rebate_type'],$v['type']);
            $v['type_word'] = $typeInfo['type_word'];
            $v['rebate_type_word'] = $typeInfo['rebate_type_word'];

            if(!empty(strpos($v['me_phone'], 'zx'))){
                $v['me_phone'] = explode('zx',$v['me_phone'])[0].'（已注销）';
                $v['me_nick_name'] = explode('zx',$v['me_nick_name'])[0].'（已注销）';
            }
            if(!empty(strpos($v['d_me_phone'], 'zx'))){
                $v['d_me_phone'] = explode('zx',$v['d_me_phone'])[0].'（已注销）';
                $v['d_me_nick_name'] = explode('zx',$v['d_me_nick_name'])[0].'（已注销）';
            }
            if($v['zd_sz'] == 0){
                $v['money'] = '-';
                $v['member_money'] = '-';
                $v['status_word'] = '-';
            }

            return $v;
        });
//        $IndexTableModel = New IndexTableModel();
//        $type_list = $IndexTableModel->getList('fa_finance_type',"`id` > 0","*",'type asc,sz_type asc');
//        foreach ($type_list as $k=>$v){
//            $type_list[$k]['type_word'] = $this->getTypeWord($v['type'],$v['sz_type'],$v['name']);
//        }
        $arr = $this->getFundSearchList();
        //收入可提现油票
        $k_stamp_income_arr = $arr['data']['k_stamp_income'];
        //收入不可提现油票
        $bk_stamp_income_arr = $arr['data']['bk_stamp_income'];
        //支出可 提现或不可提现 油票
        $stamp_disburse_arr = $arr['data']['stamp_disburse'];
        //曝光收入
        $exposure_income_arr = $arr['data']['exposure_income'];
        //曝光支出
        $exposure_disburse_arr = $arr['data']['exposure_disburse'];

        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
//            'type_list'  => $type_list,
            'page'  => $data->render(),
            'total' => $data->total(),
            'k_stamp_income_arr' => $k_stamp_income_arr,
            'bk_stamp_income_arr' => $bk_stamp_income_arr,
            'stamp_disburse_arr' => $stamp_disburse_arr,
            'exposure_income_arr' => $exposure_income_arr,
            'exposure_disburse_arr' => $exposure_disburse_arr,
            'zhuanword' => $zhuanword,
            'txword' => $txword,
            'mqword' => $mqword,
        ]);
        return $this->fetch();
    }


    /**
     * 转换 账单类型 为文字描述
     * User:@hang
     */
    public function getTypeWord($type_name,$status,$rebate_type,$type){
        $str = $type_name;
        if($type == 15){
            //通过油票提现
            return ['type_word'=>$type_name,'rebate_type_word'=>''];
        }
        if(in_array($type,[4,5,6])){
            //文字 语音 视频 相关
            switch($status){
                case '1': $str .= '收益';break;
                case '2': $str .= '消耗';break;
            }
        }
        $rebate_type_word = '';
        switch($rebate_type){
            case '0': $rebate_type_word = '【自身】';break;
            case '1': $rebate_type_word = '【上级奖励】';break;
            case '2': $rebate_type_word = '【上上级激励】';break;
        }
        return ['type_word'=>$str,'rebate_type_word'=>$rebate_type_word];
    }




    /**
     * 获取【账单筛选类型】列表
     * User:@hang
     */
    public function getFundSearchList()
    {
        $IndexTableModel = New IndexTableModel();
        $list = $IndexTableModel->getList('fa_finance_type',"`id` > 0",'CAST(id AS char) as type_id,name,type,sz_type','id asc');//全部账单类型
        $data = array();
        //收入可提现油票
        $k_stamp_income = array();
        //收入不可提现油票
        $bk_stamp_income= array();
        //支出可 提现或不可提现 油票
        $stamp_disburse = array();

        //曝光收入
        $exposure_income = array();
        //曝光支出
        $exposure_disburse = array();

        foreach ($list as $k=>$v){
            if(in_array($v['type_id'],[4,5,6,9,10,11,12,13,14,31,33,32,37,39])){
                $k_stamp_income_arr = array();
                $k_stamp_income_arr['type_id'] = $v['type_id'];
                $k_stamp_income_arr['name'] = $v['name'];
                if(in_array($v['type_id'],[4,5,6])){
                    $k_stamp_income_arr['name'] = $k_stamp_income_arr['name'].'收益';
                }
                $k_stamp_income[] = $k_stamp_income_arr;
            }
            if(in_array($v['type_id'],[7,17,18,33,34,38,39])){
                $bk_stamp_income_arr = array();
                $bk_stamp_income_arr['type_id'] = $v['type_id'];
                $bk_stamp_income_arr['name'] = $v['name'];
                $bk_stamp_income[] = $bk_stamp_income_arr;
            }
            if(in_array($v['type_id'],[1,2,3,4,5,6,8,16,19,15,32,35,36,40])){
                $stamp_disburse_arr = array();
                $stamp_disburse_arr['type_id'] = $v['type_id'];
                $stamp_disburse_arr['name'] = $v['name'];
                if(in_array($v['type_id'],[4,5,6])){
                    $stamp_disburse_arr['name'] = $stamp_disburse_arr['name'].'消耗';
                }
                $stamp_disburse[] = $stamp_disburse_arr;
            }
            if(in_array($v['type_id'],[21,24,25,27,28])){
                $exposure_income_arr = array();
                $exposure_income_arr['type_id'] = $v['type_id'];
                $exposure_income_arr['name'] = $v['name'];
                $exposure_income[] = $exposure_income_arr;
            }
            if(in_array($v['type_id'],[22,23])){
                $exposure_disburse_arr = array();
                $exposure_disburse_arr['type_id'] = $v['type_id'];
                $exposure_disburse_arr['name'] = $v['name'];
                $exposure_disburse[] = $exposure_disburse_arr;
            }
        }

        $data['k_stamp_income'] = $k_stamp_income;
        $data['bk_stamp_income'] = $bk_stamp_income;
        $data['stamp_disburse'] = $stamp_disburse;
        $data['exposure_income'] = $exposure_income;
        $data['exposure_disburse'] = $exposure_disburse;

//        $data['stamp_income'] = $IndexTableModel->getList('fa_finance_type',"`type` = 1 and `sz_type` in(1,3)",'CAST(id AS char) as type_id,name','id asc');//油票收入
//        $data['stamp_disburse'] = $IndexTableModel->getList('fa_finance_type',"`type` = 1 and `sz_type` in(2,3)",'CAST(id AS char) as type_id,name','id asc');//油票支出;
//        $data['exposure_income'] = $IndexTableModel->getList('fa_finance_type',"`type` = 2 and `sz_type` in(1,3)",'CAST(id AS char) as type_id,name','id asc');//曝光收入
//        $data['exposure_disburse'] = $IndexTableModel->getList('fa_finance_type',"`type` = 2 and `sz_type` in(2,3)",'CAST(id AS char) as type_id,name','id asc');//曝光支出
        return ['code'=>200,'msg'=>'获取用户钱包余额成功','data'=>$data];
    }


    /**
     * 收入查询
     * User:@hang
     */
    public function getrisk(Request $request)
    {
        $param = $request->param();
        $boy_member_id = 0;
        if (isset($param['member_id']) && !empty($param['member_id'])) {
            $boy_member_id = $param['member_id'];
        }
        $whehetime = '';
        if (isset($param['add_time']) && !empty($param['add_time'])) {
            $time_arr = explode(' - ', $param['add_time']);
            $start_time = strtotime($time_arr[0]);
            $end_time = strtotime($time_arr[1].'23:59:59');
            $whehetime = "add_time >= $start_time AND add_time <= $end_time";
        }
        $data = $this->getRiskMmeber($boy_member_id,$whehetime);

        $this->assign($request->get());
        $this->assign([
            'memberinfo' => $data['memberinfo'],
            'data' => $data['list'],
        ]);
        return $this->fetch();
    }


    /**
     * 查询风险收入
     * User:@hang
     */
    public function getRiskMmeber($boy_member_id,$whehetime)
    {
        $memberinfo = '暂无信息';
        $fid = 0;
        $ffid = 0;
        $fffid = 0;
        //用户信息
        $memberInfo = Db::table('fa_member')->where("member_id = '{$boy_member_id}'")->field('member_id,me_phone,me_sex,me_nick_name,me_parent')->find();
        if(!empty($memberInfo)){
            //充值金额
            $czInfo = Db::table('fa_recharge_stamp_order')->where("member_id = '{$boy_member_id}'")->where($whehetime)->sum('pay_money');
            $czMoney = empty($czInfo)?0:$czInfo;
            //钱包信息
            $fundInfo = Db::table('fa_member_fund')->where("member_id = '{$boy_member_id}'")->field('no_stamp_money')->find();
            //文字音视频消耗
            $wzyspXhInfo = Db::table('fa_finance')->where("member_id = '{$boy_member_id}' and type in(4,5,6) and chat_type in(1,2,3) and money_type = 1 and status = 2")->sum('money');
            $wzyspXh = !empty($wzyspXhInfo)?$wzyspXhInfo:0;
            //礼物消耗
            $lwXhInfo = Db::table('fa_finance')->where("member_id = '{$boy_member_id}' and type = 3 and g_id != -111 and money_type = 1 and status = 2")->sum('money');
            $lwXh = !empty($lwXhInfo)?$lwXhInfo:0;
            //开通VIP消耗
            $vipXhInfo = Db::table('fa_finance')->where("member_id = '{$boy_member_id}' and type = 19 and money_type = 1 and status = 2")->sum('money');
            $vipXh = !empty($vipXhInfo)?$vipXhInfo:0;
            //赠送VIP和特殊礼物消耗
            $zsvipXhInfo = Db::table('fa_finance')->where("member_id = '{$boy_member_id}' and ((type = 32 and money_type = 1 and status = 2) or (type = 3 and money_type = 1 and status = 2 and g_id = -111))")->sum('money');
            $zsvipXh = !empty($zsvipXhInfo)?$zsvipXhInfo:0;
            $yhPhone = '';
            if(!empty(strpos($memberInfo['me_phone'], 'zx'))){
                $yhPhone = explode('zx',$memberInfo['me_phone'])[0]."(已注销)";
            }else{
                $yhPhone = $memberInfo['me_phone'];
            }
            $memberinfo = "查询的用户信息【融云ID：{$memberInfo['member_id']} ；手机：{$yhPhone}；昵称：{$memberInfo['me_nick_name']}；充值总金额：{$czMoney} 元；文字音视频消耗：{$wzyspXh} 元；赠送礼物消耗：{$lwXhInfo} 元；开通VIP消耗：{$vipXh} ；赠送VIP和特殊礼物消耗：{$zsvipXh} ；剩余不可提现油票：{$fundInfo['no_stamp_money']}】";
            $fid = $memberInfo['me_parent'];
            $fInfo = Db::table('fa_member')->where("member_id = '{$fid}'")->field('member_id,me_phone,me_sex,me_nick_name,me_parent')->find();
            if(!empty($fInfo)){
                $ffid = $fInfo['me_parent'];
            }
            if($ffid != 0){
                $ffInfo = Db::table('fa_member')->where("member_id = '{$ffid}'")->field('member_id,me_phone,me_sex,me_nick_name,me_parent')->find();
                if(!empty($ffInfo)){
                    $fffid = $ffInfo['me_parent'];
                }
            }
        }

        $list = array();
        if(!empty($boy_member_id)){
            //从此用户身上获取过收益的 女用户
            $nvlist = Db::table('fa_finance')->where("d_member_id = '{$boy_member_id}' and g_id != -88 and money_type = 2 and status = 1")->where($whehetime)->group('member_id')->field('member_id')->order('id desc')->select();
            //从此用户身上获得过收益的 超推(女用户上级)
            $ctlist = Db::table('fa_rebate_log')->where("n_member_id = '{$boy_member_id}' and type <= 4 and grade_type = 1")->where($whehetime)->group('smember_id')->field('smember_id as member_id')->order('id desc')->select();
            if(!empty($ctlist)){
                // 步骤1：合并两个数组
                $merged = array_merge($nvlist, $ctlist);
                // 步骤2：提取所有 member_id（忽略外层数组结构）
                $memberIds = array_column($merged, 'member_id');
                // 步骤3：去重 + 重新索引（确保键连续）
                $lists = array_values(array_unique($memberIds));
                if(!empty($lists)){
                    foreach ($lists as $k=>$v){
                        $list[$k]['member_id'] = $v;
                    }
                }
            }else{
                $list = $nvlist;
            }
            //从此用户身上获得过收益的 产品(女用户上上级)
            $ctlists = Db::table('fa_rebate_log')->where("n_member_id = '{$boy_member_id}' and type <= 4 and grade_type = 2")->where($whehetime)->group('smember_id')->field('ssmember_id as member_id')->order('id desc')->select();
            if(!empty($ctlists)){
                // 步骤1：合并两个数组
                $merged = array_merge($list, $ctlists);
                // 步骤2：提取所有 member_id（忽略外层数组结构）
                $memberIds = array_column($merged, 'member_id');
                // 步骤3：去重 + 重新索引（确保键连续）
                $lists = array_values(array_unique($memberIds));
                if(!empty($lists)){
                    foreach ($lists as $k=>$v){
                        $list[$k]['member_id'] = $v;
                    }
                }
            }

            if(!empty($list)){
                //按团队分组从上往下排序
                foreach ($list as $k=>$v){
                    $info = Db::table('fa_member')->where("member_id = '{$v['member_id']}'")->field('member_id,me_phone,me_sex,me_nick_name,me_parent')->find();
                    $list[$k]['me_parent'] = $info['me_parent'];
                }
                $list = $this->getFzPx($list);//排序
//                var_dump($list);die;

                foreach ($list as $k=>$v){
                    //分隔线
                    $list[$k]['fg_word'] = '';
                    if(empty($v['me_parent'])){
                        $list[$k]['fg_word'] = '----------';
                    }
                    if(isset($list[$k+1])){
                        if($v['me_parent'] != $list[$k+1]['member_id']){
                            $list[$k]['fg_word'] = '----------';
                        }
                    }else{
                        $list[$k]['fg_word'] = '----------';
                    }


                    //开始计算各种信息
                    $memberinfostr = '';
                    //女孩信息
                    $info = Db::table('fa_member')->where("member_id = '{$v['member_id']}'")->field('member_id,me_phone,me_sex,me_nick_name,me_parent')->find();
                    $me_parent_word = empty($info['me_parent'])?'无上级':'上级'.$info['me_parent'];
                    if(!empty(strpos($info['me_phone'], 'zx'))){
                        $info['me_phone'] = explode('zx',$info['me_phone'])[0];
                        $memberinfostr = "【女ID：{$info['member_id']}（{$me_parent_word}） ；手机：{$info['me_phone']}(已注销)；昵称：{$info['me_nick_name']}】";
                    }else{
                        $memberinfostr = "【女ID：{$info['member_id']}（{$me_parent_word}） ；手机：{$info['me_phone']}；昵称：{$info['me_nick_name']}】";
                    }
                    $list[$k]['memberinfostr'] = $memberinfostr;

                    //作为女孩 文字语音视频收益
                    $nvwz = Db::table('fa_finance')->where("member_id = '{$v['member_id']}' and d_member_id = '{$boy_member_id}' and money_type = 2 and status = 1 and chat_type in(1,2,3) and g_id >= 0")->where($whehetime)->sum('money');
                    //作为超推 文字语音视频收益
                    $ctwz = Db::table('fa_rebate_log')->where("smember_id = '{$v['member_id']}' and type <= 3 and n_member_id = '{$boy_member_id}' and grade_type = 1")->where($whehetime)->sum('profit_money');
                    //作为运营 文字语音视频收益
                    $yywz = Db::table('fa_rebate_log')->where("ssmember_id = '{$v['member_id']}' and type <= 3 and n_member_id = '{$boy_member_id}' and grade_type = 2")->where($whehetime)->sum('profit_money');
                    //作为产品 文字语音视频收益
                    $cpwz = Db::table('fa_rebate_log')->where("sssmember_id = '{$v['member_id']}' and type <= 3 and n_member_id = '{$boy_member_id}' and grade_type = 3")->where($whehetime)->sum('profit_money');
                    $wz = delete0(bcadd(bcadd(bcadd($nvwz,$ctwz,4),$yywz,4),$cpwz,4));//文字语音视频收益


                    //作为女孩 礼物收益
                    $nvlw = Db::table('fa_finance')->where("member_id = '{$v['member_id']}' and d_member_id = '{$boy_member_id}' and type = 13 and money_type = 2 and status = 1 and chat_type = 0 and g_id != -111")->where($whehetime)->sum('money');
                    //作为超推 礼物收益
                    $ctlw = Db::table('fa_rebate_log')->where("smember_id = '{$v['member_id']}' and type = 4 and n_member_id = '{$boy_member_id}' and grade_type = 1")->where($whehetime)->sum('profit_money');
                    //作为运营 礼物收益
                    $yylw = Db::table('fa_rebate_log')->where("ssmember_id = '{$v['member_id']}' and type = 4 and n_member_id = '{$boy_member_id}' and grade_type = 2")->where($whehetime)->sum('profit_money');
                    //作为产品 礼物收益
                    $cplw = Db::table('fa_rebate_log')->where("sssmember_id = '{$v['member_id']}' and type = 4 and n_member_id = '{$boy_member_id}' and grade_type = 3")->where($whehetime)->sum('profit_money');
                    $lw = delete0(bcadd(bcadd(bcadd($nvlw,$ctlw,4),$yylw,4),$cplw,4));//礼物收益


                    //充值收益
                    $cz = Db::table('fa_finance')->where("member_id = '{$v['member_id']}' and d_member_id = '{$boy_member_id}' and type = 11 and money_type = 2 and status = 1 and rebate_type != 0 and g_table = 'fa_recharge_stamp_order'")->where($whehetime)->sum('money');

                    //开通VIP收益
                    $ktvip = Db::table('fa_finance')->where("member_id = '{$v['member_id']}' and d_member_id = '{$boy_member_id}' and type = 11 and money_type = 2 and status = 1 and rebate_type != 0 and g_table = 'fa_recharge_vip_order'")->where($whehetime)->sum('money');

                    //赠送VIP和特殊礼物收益
                    $zsvip = Db::table('fa_finance')->where("member_id = '{$v['member_id']}' and d_member_id = '{$boy_member_id}' and ((type = 32 and money_type = 2 and status = 1 and g_table = 'fa_recharge_vip_order') or (type = 13 and money_type = 2 and status = 1 and g_id = -111))")->where($whehetime)->sum('money');

                    //合计
                    $hj = delete0(bcadd(bcadd(bcadd(bcadd($wz,$lw,4),$cz,4),$ktvip,4),$zsvip,4));

                    $arr = array();
                    $arr['wz'] = "【文字音视频收益：$wz 元】";
                    $arr['lw'] = "【礼物收益：$lw 元】";
                    $arr['cz'] = "【充值收益：$cz 元】";
                    $arr['ktvip'] = "【开通VIP收益：$ktvip 元】";
                    $arr['zsvip'] = "【赠送VIP和特殊礼物收益：$zsvip 元】";
                    $arr['hj'] = "【合计：$hj 元】";
                    $arr['sjinfo'] = '（无关系，但获得过收益）';
                    if($v['member_id'] == $fid){
                        $arr['sjinfo'] = '（被查询者的上级）';
                    }
                    if($v['member_id'] == $ffid){
                        $arr['sjinfo'] = '（被查询者的上上级）';
                    }
                    if($v['member_id'] == $fffid){
                        $arr['sjinfo'] = '（被查询者的上上上级）';
                    }
                    $list[$k]['px'] = $hj;
                    $list[$k]['arr'] = $arr;
                }
            }
        }
//        usort($list, 'compareAges');//按照合计收益从大到小排序
//        var_dump($list);die;
        return ['list'=>$list,'memberinfo'=>$memberinfo];
    }

    public function getFzPx($original)
    {
        // 1. 构建映射：快速查找节点和子节点
        $idMap = [];         // member_id => 节点数据
        $childrenMap = [];   // me_parent => 子节点列表（记录谁的上级是当前节点）
        foreach ($original as $item) {
            $memberId = $item['member_id'];
            $parentId = $item['me_parent'];
            $idMap[$memberId] = $item;
            // 记录子节点（当前节点的上级是parentId，所以parentId的子节点包含当前节点）
            if (!isset($childrenMap[$parentId])) {
                $childrenMap[$parentId] = [];
            }
            $childrenMap[$parentId][] = $memberId;
        }
        // 2. 找出所有“叶子节点”（没有子节点的节点，即最底层的子节点）
        $leafNodes = [];
        foreach ($idMap as $memberId => $item) {
            // 如果当前节点没有子节点，就是叶子节点
            if (!isset($childrenMap[$memberId]) || empty($childrenMap[$memberId])) {
                $leafNodes[] = $memberId;
            }
        }
        // 3. 从叶子节点向上追溯，构建完整链条（子→父→根）
        $chains = [];
        $processed = []; // 记录已处理的节点，避免重复
        foreach ($leafNodes as $leafId) {
            $chain = [];
            $currentId = $leafId;
            // 向上遍历直到无上级（或上级不在数组中）
            while (true) {
                // 防止循环引用（如A的上级是B，B的上级是A）
                if (in_array($currentId, $processed)) {
                    break;
                }
                $chain[] = $idMap[$currentId]; // 加入当前节点
                $processed[] = $currentId;     // 标记为已处理
                $parentId = $idMap[$currentId]['me_parent'];
                // 如果上级不存在于数组中，结束链条
                if (!isset($idMap[$parentId])) {
                    break;
                }
                $currentId = $parentId; // 继续向上找父节点
            }
            // 链条不为空则加入结果
            if (!empty($chain)) {
                $chains[] = $chain;
            }
        }
        // 4. 按链条第一个元素的member_id排序（确保顺序：588→120→533→207）
        usort($chains, function ($a, $b) {
            return $a[0]['member_id'] - $b[0]['member_id'];
        });
        // 5. 合并所有链条，得到最终结果
        $result = [];
        foreach ($chains as $chain) {
            $result = array_merge($result, $chain);
        }
        return $result;
    }



    /**
     * 团队女孩送礼物统计
     * User:@hang
     */
    public function girlpushgift(Request $request)
    {
        $param = $request->param();
        $whehe = array();
        if (isset($param['girl_djparent']) && !empty($param['girl_djparent'])) {
            $whehe[] = ['b.member_id','=',$param['girl_djparent']];
        }
        $whehetime = '';
        $whehetimelw = '';
        if (isset($param['add_time']) && !empty($param['add_time'])) {
            $time_arr = explode(' - ', $param['add_time']);
            $start_time = strtotime($time_arr[0]);
            $end_time = strtotime($time_arr[1]);
            $whehetime = "a.add_time >= $start_time AND a.add_time <= $end_time";
            $whehetimelw = " and lw.add_time >= $start_time AND lw.add_time <= $end_time";
        }

        $data = Db::table('fa_gift_give_log')
            ->alias('a')
            ->join("fa_member b",'a.girl_djparent = b.member_id','LEFT')
            ->where("a.is_girl_push = 1 and a.girl_djparent != 0")
            ->where($whehe)
            ->where($whehetime)
            ->field("a.girl_djparent,b.me_uid,b.me_phone,b.me_nick_name,b.me_sex,(select sum(lw.gift_money_all) from fa_gift_give_log lw where lw.girl_djparent = b.member_id".$whehetimelw.") as lw_all_money")
            ->group('a.girl_djparent')
            ->order('lw_all_money desc')
            ->paginate($this->admin['per_page'],false,['query'=>request()->param()]);

        $adminid = $this->uid;
        $data->each(function ($v, $k)use($adminid) {
            //只有超管能看全部手机号
            if($adminid != 1){
                $v['me_phone'] = hide_phone_number($v['me_phone']);
            }

            if(!empty(strpos($v['me_phone'], 'zx'))){
                $v['me_phone'] = explode('zx',$v['me_phone'])[0].'（已注销）';
                $v['me_nick_name'] = explode('zx',$v['me_nick_name'])[0].'（已注销）';
            }

            return $v;
        });

        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }



    /**
     * 超推团队充值详情
     * User:@hang
     */
    public function getextrainfo(Request $request)
    {
        $param = $request->param();
        $ct_member_id = 0;
        if (isset($param['member_id']) && !empty($param['member_id'])) {
            $ct_member_id = $param['member_id'];
        }else{
            $this->assign($request->get());
            $this->assign([
                'allczword' => '',
                'xtmr' => '',
                'data' => [],
                'ptsy' => '',
            ]);
            return $this->fetch();
        }
        $whehetime = '';
        if (isset($param['add_time']) && !empty($param['add_time'])) {
            $time_arr = explode(' - ', $param['add_time']);
            $start_time = strtotime($time_arr[0]);
            $end_time = strtotime($time_arr[1].'23:59:59');
            $whehetime = " and add_time >= $start_time AND add_time <= $end_time";
        }

        $data = [];
        $resword = '';
        $ptsy = 0;
        //一共充值
        $allMoney = DB::table('fa_recharge_stamp_order')->where("`ffid` = '{$ct_member_id}'".$whehetime)->sum('all_stamp_num');
        $allczword = "一共充值：{$allMoney}";
        $resword = "计算平台剩余：{$allMoney}";
        $ptsy = $allMoney;
        //规则列表
        $gzList = Db::table('fa_extra_award_config')->where("`c_member_id` = '{$ct_member_id}'")->orderRaw('jl_bl+0 asc')->select();
        if(empty($gzList)){
            $gzList = Db::table('fa_extra_award_config')->where("`c_member_id` = '-1'")->orderRaw('jl_bl+0 asc')->select();
        }
        if(!empty($gzList)){
            $ewFmoney = 0;
            //额外增加比例 充值信息
            foreach ($gzList as $k=>$v){
               $ewfMoney = DB::table('fa_recharge_stamp_order')->where("`ffid` = '{$ct_member_id}' and `ew_jl` = '{$v['jl_bl']}'".$whehetime)->sum('ew_jl_money');
               $data[]['word'] = "额外奖励：充值 {$ewfMoney} （93% 基础上多给 {$v['jl_bl']} %）";
               $resword .= " - （{$ewfMoney} x ".(0.93 + $v['jl_bl'] / 100)."）";
               $ewFmoney = bcadd($ewFmoney,$ewfMoney,4);//参与额外给的充值金额总和
               $ptsy = bcsub($ptsy,bcmul($ewfMoney,0.93 + $v['jl_bl'] / 100,4),4);
            }
        }
        //默认比例 充值信息
        $mrblMoney = delete0(bcsub($allMoney,$ewFmoney,4));
        $resword .= " - （{$mrblMoney} x ".(0.93)."）";
        $xtmr = '默认比例：充值 '.$mrblMoney.' （93%）';
        //平台剩余
        $ptsy = delete0(bcsub($ptsy,bcmul($mrblMoney,0.93,4),4));

//
//        var_dump($data);
//        var_dump($resword);
//        var_dump($ewFmoney);
//        var_dump($ptsy);
//        die;

        $this->assign($request->get());
        $this->assign([
            'allczword' => $allczword,
            'xtmr' => $xtmr,
            'data' => $data,
            'ptsy' => $resword.' = '.$ptsy,
        ]);
        return $this->fetch();
    }



}
